<?php

namespace App\Models;

use App\Libraries\Common\CommonFun;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RsTeam extends Model
{
    use HasFactory;
    public $timestamps=false;
    protected $table='rs_team';
    protected $fillable=['team_no','team_name','create_time','team_person','team_person_id','monitor_team_uid'];

    //查询数据
    public static function lists($page = 1, $limit = 20, $params = []){
        $ary_where = array();
        $tema_name=data_get($params,'tema_name',false);

        if($tema_name){
            $ary_where[] = ['team_name', 'like', '%'.$tema_name.'%'];
        }

        $query = self::where($ary_where);
        $count = $query->count();
        $data = $query->offset(CommonFun::getOffset($page, $limit))->limit($limit)->orderBy('id', 'desc')->get()->map(function (RsTeam $rebate) use ($count) {
            $rebate = $rebate->attributesToArray();
            $name=RsUsers::query()->where('user_id',$rebate['team_person'])->first();
            $rebate['name']=isset($name)?$name->username:'';
           // $rebate['is_show_home'] = $rebate['is_show_home']==0 ?'否' : '是';

            return $rebate;
        })->toArray();

        return $data ? compact('count', 'data') : false;
    }


    //对团队进行添加
    public static function created($data){

        if(!$data['id']){
            unset($data['id']);
            $data['create_time']=date('Y-m-d');
            $id= self::create($data)->id;
        }else{
            $model=self::where(['id'=>$data['id']])->first();
            $model->team_name=$data['team_name'];
            $model->team_person=$data['team_person'];
            $model->team_person_id=$data['team_person_id'];
            $model->monitor_team_uid=$data['monitor_team_uid'];
            $model->save();
            $id=$model->id;
        }
        //将id更新至权限表中
        RsTeamUser::where(['team_id'=>''])->orWhere(['team_id'=>null])->update(['team_id'=>$id]);
        return true;

    }
}
